package cc.linker.steplink.crm.merchant.controller.acs;


import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.service.acs.MerchantInfoService;
import cc.linker.steplink.crm.merchant.service.acs.PageService;
import cc.linker.steplink.crm.merchanth5.service.acs.MerchantSalerService;
import cc.linker.steplink.crm.response.GlobalException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;

/**
 * 页面管理
 */
@RequestMapping("/page")
@RestController
public class PageController {

    @Autowired
    private PageService pageService;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private MerchantSalerService merchantSalerService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserInfoUtil userInfoUtil;

    /**
     * 页面管理-新增-新增模块（商品）
     *
     * @param param
     * @param session
     * @return
     */
    @PostMapping("/addgoodsmodule")
    public void addGoodsmodule(@RequestBody Map<String, Object> param, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        if (StringUtils.isEmpty(param.get("showStyle")) || StringUtils.isEmpty(param.get("goodsTitle"))
                || StringUtils.isEmpty(param.get("moduleName")) || StringUtils.isEmpty(param.get("showNum"))) {
            throw GlobalException.build("请填写完整");
        }
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        if (ifSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
        } else {
            param.put("customerId", orgId);
        }
        param.put("orgId", orgId);
        // v1.11.15 支持 新增知识付费商品 默认视频组件
        Integer moduleType = StringUtils.isEmpty(param.get("moduleType")) ? 3 : (Integer) param.get("moduleType");
        param.put("moduleType", moduleType);

        if (!StringUtils.isEmpty(param.get("id"))) {
            pageService.updateModule(param);
        } else {
            param.put("id", UUID.randomUUID().toString());
            param.put("sort", StringUtils.isEmpty(param.get("sort")) ? 1 : param.get("sort"));
            pageService.addModule(param);
        }
        // 插入自定义的商品组件
        if ("2".equals(param.get("showStyle").toString())) {
            pageService.addGoodsList(param);
        }
        stringRedisTemplate.delete("home:pagelist_" + orgId + "_" + param.get("customerId").toString());
    }

    /**
     * 获取模块（商品）详情
     *
     * @param id
     * @param session
     * @return
     */
    @GetMapping("/getgoodsmodule")
    public Map<String, Object> getGoodsModule(@RequestParam String id, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        if (StringUtils.isEmpty(id)) {
            throw GlobalException.build("参数错误");
        }
        String orgId = userinfo.getOrgId();

        boolean ifSaler = userinfo.getSaler();
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("orgId", orgId);
        param.put("sale", 0);
        if (ifSaler) {
            param.put("sale", 1);
        }
        return pageService.getGoodsModule(param);
    }

    /**
     * 页面管理-新增-新增模块（图片广告和图文导航）
     *
     * @param param
     * @param session
     * @return
     */
    @PostMapping("/addimagemodule")
    public void addImagemodule(@RequestBody Map<String, Object> param,HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        if (ifSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
        } else {
            param.put("customerId", orgId);
        }
        param.put("orgId", orgId);
        pageService.addImagemodule(param);
        stringRedisTemplate.delete("home:pagelist_" + orgId + "_" + param.get("customerId").toString());
    }

    /**
     * 页面管理列表
     *
     * @param session
     * @return
     */
    @GetMapping("/list")
    public List<Map<String, Object>> list(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Boolean isSales = userinfo.getSaler();
        String adminId = userinfo.getAdminId();
        String orgId = userinfo.getOrgId();
        String createTime;
        String customerId = "";
        if (isSales) {
            Map<String, Object> cInfo = pageService.getSaleInfoByAdminId(adminId);
            createTime = cInfo.get("createTime").toString();
            customerId = cInfo.get("customerId").toString();
        } else {
            createTime = pageService.getCtimeByOrgId(orgId);
            ;
        }
        List<Map<String, Object>> result = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("name", "商城页面");
        map1.put("createTime", createTime);
        map1.put("customerId", customerId);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("name", "个人中心");
        map2.put("createTime", createTime);
        result.add(map1);
        result.add(map2);
        return result;
    }

    /**
     * 页面管理模块列表
     *
     * @param session
     * @return
     */
    @GetMapping("/modulelist")
    public List<Map<String, Object>> moduleList(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        return pageService.moduleList(customerId);
    }

    /**
     * 删除模板
     *
     * @param id
     * @param session
     */
    @GetMapping("/delmodule")
    public void delModule(String id, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        if (StringUtils.isEmpty(id)) {
            throw GlobalException.build("请传入模板ID");
        }
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }

        pageService.delModule(id, customerId);
        stringRedisTemplate.delete("home:pagelist_" + orgId + "_" + customerId);
    }

    /**
     * 获取模板 图片广告和图文导航
     *
     * @param id
     * @return
     */
    @GetMapping("/getmodule")
    public Map<String, Object> getModule(String id) {
        if (StringUtils.isEmpty(id)) {
            throw GlobalException.build("请传入模板ID");
        }
        Map<String, Object> res = pageService.getModule(id);
        List<Map<String, Object>> contents = pageService.getModuleImage(id);
        res.put("contents", contents);
        return res;
    }

    /**
     * 获取模板 报名组件
     * v1.11.15
     *
     * @param id
     * @return
     */
    @GetMapping("/getenrollmodule")
    public Map<String, Object> getEnrollModule(String id) {
        if (StringUtils.isEmpty(id)) {
            throw GlobalException.build("请传入模板ID");
        }
        Map<String, Object> res = pageService.getEnrollModule(id);
        List<Map<String, Object>> contents = pageService.getEnrollImage(id);
        res.put("contents", contents);
        return res;
    }

    /**
     * 更新排序
     */
    @PostMapping("/sortmodule")
    public void sortModule(@RequestBody List<Map<String, Object>> param, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        pageService.sortModule(param, customerId);
        stringRedisTemplate.delete("home:pagelist_" + orgId + "_" + customerId);
    }


    @PostMapping("/goodslist")
    public PageInfo goodsList(
            @RequestBody Map<String, Object> param,
            HttpServletRequest request
    ) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        param.put("sale", 0);
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("sale", 1);
        }
        param.put("customerId", customerId);
        param.put("orgId", orgId);
        param.put("type", "".equals(param.get("type")) ? null : param.get("type"));
        //是否是积分商城选商品
        Integer isIntegralMall = 0;
        if(!StringUtils.isEmpty(param.get("isIntegralMall"))){
            isIntegralMall = Integer.valueOf(param.get("isIntegralMall").toString());
        }
        param.put("isIntegralMall",isIntegralMall);
        //是否可以选择虚拟商品
        Integer isVirtual = -1;
        if(!StringUtils.isEmpty(param.get("isVirtual"))){
            isVirtual = Integer.valueOf(param.get("isVirtual").toString());
        }
        param.put("isVirtual",isVirtual);
        Integer pageIndex = StringUtils.isEmpty(param.get("pageIndex")) ? 1 : Integer.parseInt(param.get("pageIndex").toString());
        Integer pageSize = StringUtils.isEmpty(param.get("pageSize")) ? 10 : Integer.parseInt(param.get("pageSize").toString());
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(pageService.goodsList(param));
    }

    @GetMapping("/modulegoodslist")
    public List<Map<String, Object>> moduleGoodsList(
            @RequestParam(value = "id") String id,
            HttpServletRequest request
    ) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        boolean ifSaler = userinfo.getSaler();
        Map<String, Object> param = new HashMap<>();
        param.put("sale", 0);
        if (ifSaler) {
            param.put("sale", 1);
        }
        param.put("id", id);
        return pageService.moduleGoodsList(param);
    }

    /**
     * 新增修改优惠券组件
     */
    @PostMapping("/addcouponmodule")
    public void addCouponModule(@RequestBody Map<String, Object> param,HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        if (StringUtils.isEmpty(param.get("moduleName"))) {
            throw GlobalException.build("请填写模块名称");
        }
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        if (ifSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
        } else {
            param.put("customerId", orgId);
        }
        param.put("orgId", orgId);
        param.put("moduleType", 6);
        if (!StringUtils.isEmpty(param.get("id"))) {
            pageService.updateModule(param);
        } else {
            param.put("id", UUID.randomUUID().toString());
            param.put("sort", StringUtils.isEmpty(param.get("sort")) ? 1 : param.get("sort"));
            pageService.addModule(param);
        }
        // 插入优惠券
        pageService.addGoodsList(param);
        stringRedisTemplate.delete("home:pagelist_" + orgId + "_" + param.get("customerId").toString());
    }

    /**
     * 获取优惠券组件
     */


    /****************************新版页面装修功能**v1.12.6版本***************************************************/

    /**
     * 删除页面
     * 软删除
     */
    @GetMapping("/deletepage")
    public void deletePage(Integer id, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        if (StringUtils.isEmpty(id)) {
            throw GlobalException.build("参数不正确");
        }
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        pageService.deletePage(id, customerId, orgId);
    }


    /**
     * 列表 页面
     * keywords  页面名称 模糊搜索
     * pageType  正常页面 1 ; 草稿 2 ; 不传或者空 默认所有
     * pageIndex 分页-页码 默认1
     * pageSize  分页-页数 默认10
     *
     * @return
     */
    @GetMapping("/pagelist")
    public PageInfo pageList(
            @RequestParam(value = "keywords", required = false) String keywords,
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            @RequestParam(value = "pageType", required = false) Integer pageType,
            @RequestParam(value = "pageKind", required = false,defaultValue = "1") Integer pageKind,
            @RequestParam(value = "order", defaultValue = "createTime", required = false) String order,
            @RequestParam(value = "sort", defaultValue = "1",required = false) Integer sort,
            @RequestParam(value = "blankness", defaultValue = "0",required = false) Integer blankness,
            HttpServletRequest request
    ) throws UnsupportedEncodingException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        Map<String, Object> param = new HashMap<>();
        if (!StringUtils.isEmpty(keywords)) {
            keywords = URLDecoder.decode(keywords.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            keywords = keywords.replaceAll("%", "\\\\%");
        }
        param.put("keywords", keywords);
        param.put("pageType", pageType);
        param.put("customerId", customerId);
        param.put("pageKind", pageKind);
        param.put("blankness", blankness);
        param.put("order", order);
        if(1==sort){
            param.put("sort", "desc");
        }else{
            param.put("sort", "asc");
        }
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(pageService.pageList(param));
    }

    /**
     * 新增保存页面（草稿）
     */
    @PostMapping("/savepage")
    public void savePage(@RequestBody Map<String, Object> param, HttpServletRequest request) throws IOException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        param.put("orgId", orgId);
        param.put("customerId", customerId);
        pageService.savePage(param);
        // 清除缓存 更新h5页面
        int pageId = Integer.parseInt(param.get("id").toString());
        String key1 = "pageInfo:" + pageId + ":" + 1;
        String key2 = "pageInfo:" + pageId + ":" + 0;
        stringRedisTemplate.delete(key1);
        stringRedisTemplate.delete(key2);
    }

    /**
     * 获取页面详情 （包括草稿）
     *
     * @return
     */
    @GetMapping("/getpage")
    public Map<String, Object> getPage(Integer id,HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        return pageService.getPage( id,customerId);
    }

    /**
     * 获取h5页面详情 （包括草稿）  预览功能
     *
     * @return
     */
    @GetMapping("/geth5page")
    public Map<String, Object> getH5Page(Integer id,Integer isAll,HttpServletRequest request) {
        if(StringUtils.isEmpty(isAll)){
            isAll = 0;
        }
        return merchantSalerService.getPageInfo(id, isAll,true,request,false,null);
    }


    /**
     * 保存底部导航
     */
    @PostMapping("/savefooter")
    public void saveFooter(@RequestBody Map<String, Object> param,HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        param.put("orgId", orgId);
        param.put("customerId", customerId);
        pageService.saveFooter(param);

        // 清除缓存 更新h5页面
        String key = "footerList:" + customerId;
        stringRedisTemplate.delete(key);
    }

    /**
     * pc端获取底部导航
     *
     * @param session
     * @return
     */
    @GetMapping("/getfooter")
    public Map<String, Object> getFooter(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }

        return pageService.getFooter(customerId);
    }

    /**
     * 图片地址转化为base64返回
     *
     * @param url
     * @return
     */
    @GetMapping("/picurltobase")
    public String picUrlToBase64(
            String url
    ) {
        String encoded = "";
        try {
            URL picUrl = new URL(url);
            HttpURLConnection con = (HttpURLConnection) picUrl.openConnection();
            con.setRequestMethod("GET");
            con.setConnectTimeout(4 * 1000);
            //通过输入流获取图片数据 
            InputStream input = con.getInputStream();
            byte[] bytes = IOUtils.toByteArray(input);
            encoded = Base64.getEncoder().encodeToString(bytes);
        } catch (IOException e) {
            throw GlobalException.build("图片地址错误");
        }
        return encoded;
    }

    /**
     * 正常页面下拉列表
     * @param session
     * @return
     */
    @GetMapping("/getpagelist")
    public List<Map<String,Object>> getPageList(Integer pageKind,HttpServletRequest request)
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }

        return pageService.getPageList(customerId,pageKind);
    }

    /**
     * 将页面设置为首页
     * @param session
     * @param id
     */
    @GetMapping("/setindexpage")
    public void setIndexPage(
            HttpServletRequest request,
            Integer id
    )
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        pageService.setIndexPage(id,customerId);

        String key = "footerList:" + customerId;
        stringRedisTemplate.delete(key);
    }


    /**
     * 编辑时的预览功能
     */
    @PostMapping("/saveeditpage")
    public Map<String,Object> saveEditPage(@RequestBody Map<String, Object> param, HttpServletRequest request) throws IOException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        param.put("orgId", orgId);
        param.put("customerId", customerId);
        return pageService.saveEditPage(param,request);
    }

    /**
     * 查询分组下是否有数据
     * @param goodsGroupId
     * @return
     */
    @GetMapping("/getgoodsgroupnum")
    public int getGoodsGroupNum(Integer goodsGroupId){
        return pageService.getGoodsGroupNum(goodsGroupId);
    }
}
